﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using MicropleSoft.WmsServiceLibrary.Data;
using MicropleSoft.WmsServiceLibrary.Domain;
using MicropleSoft.WmsServiceLibrary.SqlServer.EFModel;
using MicropleSoft.WmsServiceLibrary.Util;

namespace MicropleSoft.WmsServiceLibrary.SqlServer
{
    public partial class WmsUserServiceSqlServer
    {
        public void Save4EncryptPassword(List<IWmsUser> wmsUsers, List<string> notUpdateProperties)
        {
            using (var ctx = GetContext())
            {
                foreach (var wmsUser in wmsUsers)
                {
                    //说明1：
                    //必须采用new WMS_USER()
                    //如果采用 ctx.CreateObject<WMS_USER>()的话，则对象状态为added，具体原因如2：
                    var entity =   new WMS_USER();

                    DomainObject2EntityObject(wmsUser, entity,Properties,EntityKeyList);

                    //说明2：
                    //此处必须使用Attach，如果使用AddToWMS_USER(entity)则entity对象的状态自动变成added，而且
                    //如果要修改状态必须采用ctx.ObjectStateManager.ChangeObjectState，这个方法会将全部字段都当做更新，
                    //这样就不能部分更新对象字段了。
                    ctx.WMS_USER.Attach(entity);

                    if(wmsUser.DomainObjectState == DomainEntityState.Updated)
                    {
                        var stateEntry = ctx.ObjectStateManager.GetObjectStateEntry(entity);
                      
                        foreach (PropertyInfo property in Properties)
                        {
                            if (EntityKeyList.Contains(property.Name))
                            {
                                continue;
                            }
                            if (! notUpdateProperties.Contains(property.Name))
                            {
                                var attriList = property.GetCustomAttributes(typeof(DataFieldNameAttribute), false);
                                if (attriList.Count() > 0)
                                {
                                    stateEntry.SetModifiedProperty(((DataFieldNameAttribute)attriList[0]).FieldName);
                                }
                            }
                        }
                    }
                    else
                    {
                        entity.PASSWD = Security.Cryptographer.CryptoMd5(wmsUser.Passwd);
                        ctx.ObjectStateManager.ChangeObjectState(entity,
                                                           StaticUtil.TranslateState(wmsUser.DomainObjectState));
                    }
                }

                ctx.SaveChanges();
            }
        }
    }
}
